package com.itjin.filter;

import com.itjin.config.JwtConfig;
import com.itjin.model.domain.entity.User;
import com.itjin.service.UserService;
import com.itjin.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(urlPatterns = "/api/*")
public class JwtAuthenticationFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

    @Resource
    private UserService userService;

    @Resource
    private JwtConfig jwtConfig;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化配置
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String token = httpRequest.getHeader("Authorization");

        if (StringUtils.hasText(token) && token.startsWith("Bearer ")) {
            token = token.substring(7);
            try {
                log.info("收到请求：{}，Token：{}", httpRequest.getRequestURI(), token);
                Claims claims = JwtUtil.extractClaim(token);
                String userAccount = claims.getSubject();

                // 从数据库获取最新用户状态
                User currentUser = userService.getOne(new QueryWrapper<User>()
                        .eq("userAccount", userAccount)
                        .select("id", "userRole", "userStatus"));

                if (currentUser != null) {
                    log.info("成功获取用户信息：{}", currentUser);
                    log.debug("解析后的Claims：{}", claims.toString());
                    log.debug("数据库查询条件：userAccount={}", userAccount);
                    log.debug("查询结果：{}", currentUser);
                    request.setAttribute("currentUser", currentUser);
                } else {
                    log.warn("用户不存在：{}", userAccount);
                }

            } catch (ExpiredJwtException e) {
                log.warn("JWT已过期: {}", e.getMessage());
            } catch (UnsupportedJwtException e) {
                log.warn("不支持的JWT格式: {}", e.getMessage());
            } catch (MalformedJwtException e) {
                log.warn("无效的JWT: {}", e.getMessage());
            } catch (IllegalArgumentException e) {
                log.warn("JWT解析参数错误: {}", e.getMessage());
            } catch (Exception e) {
                log.error("JWT处理异常: {}", e.getMessage());
            }
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 销毁过滤器
    }
}